﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace MyMVC.DAL
{
    /// <summary>
    /// 数据库连接操作
    /// </summary>
    public class DBHelper
    {
        //定义数据库连接字符串
        private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();

        public static SqlDataReader GetReader(string sql) {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql,conn);
            try
            {
                conn.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


        public static int NonQuery(string sql, CommandType type = CommandType.Text, params SqlParameter[] sps)
        {
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = ParamCommand(sql, conn, type, sps);
                return cmd.ExecuteNonQuery();
            }
        }
        private static SqlCommand ParamCommand(string sql, SqlConnection conn, CommandType type, SqlParameter[] sps)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.CommandType = type;
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            if (sps != null)
            {
                cmd.Parameters.AddRange(sps);
            }
            return cmd;
        }

        public static SqlDataReader Reader(string sql, CommandType type = CommandType.Text, params SqlParameter[] sps)
        {
            SqlConnection conn = new SqlConnection(connString);

            SqlCommand cmd = ParamCommand(sql, conn, type, sps);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

    }
}
